﻿using System;
using System.ServiceModel;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Validation.Integration.WCF;

namespace Metro.Kashikoi.Common.ExceptionHandling
{
    /// <summary>
    /// Exception handler.
    /// </summary>
    public static class ExceptionHandler
    {
        /// <summary>
        /// Handles the specified exception.
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <param name="policy">The policy.</param>
        public static void Handle(Exception exception, string policy)
        {
            Exception newEx;
            bool reThrow = ExceptionPolicy.HandleException(exception, policy, out newEx);
            if (reThrow)
            {
                if (newEx != null)
                {
                    throw newEx;
                }
                else
                {
                    throw exception;
                }
            }
        }

        /// <summary>
        /// Gets the message from the <c>FaultException</c>.
        /// </summary>
        /// <param name="exception">The fault exception.</param>
        /// <returns>The error message.</returns>
        public static string GetMessage(FaultException<ValidationFault> exception)
        {
            var fault = exception.Detail;
            var msg = new StringBuilder();
            foreach (var validationResult in fault.Details)
            {
                msg.Append("Failed to validate the property ");
                msg.AppendLine(validationResult.Key);
                msg.AppendLine(validationResult.Message);
            }
            return msg.ToString();
        }

        /// <summary>
        /// Gets the message from the <c>FaultException</c>.
        /// </summary>
        /// <param name="exception">The fault exception.</param>
        /// <returns>The error message.</returns>
        public static string GetMessage(FaultException<ServiceFault> exception)
        {
            var fault = exception.Detail;
            var msg = new StringBuilder();
            msg.AppendLine(fault.ErrorMessage);
            if (!string.IsNullOrEmpty(fault.DetailedMessage))
            {
                msg.AppendLine(fault.DetailedMessage);
            }
            return msg.ToString();
        }
    }
}
